import 'package:baselib/utils/drawable_base_util.dart';
import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/px_base_util.dart';
import 'package:baselib/utils/string_base_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:easy_refresh/easy_refresh.dart';
/**
 * author：lx
 * 基于SmartRefresher的封装：下拉刷新、上拉加载更多、空视图、错误视图、重新加载
 * 1.空视图的时候只能下拉刷新，不能上拉
 * 2.错误视图的时候只能重新加载，不能上拉和下拉
 */

enum RefreshState {
  HEAD_ERROR,
  FOOT_ERROR,
  HEAD_EMPTY,
  FOOT_EMPTY,
  HEAD_LOADING,
  FOOT_LOADING,
  NOT_ENOUGHPAGESIZE_HEAD,
  NOT_ENOUGHPAGESIZE_FOOT,
  OK,
  INIT,
}
class CommRefreshController extends EasyRefreshController {
  final bool commControlFinishRefresh;
  final bool commControlFinishLoad;
  RefreshState state = RefreshState.OK;


  CommRefreshController({
    this.commControlFinishRefresh = true,
    this.commControlFinishLoad = true,
    this.state = RefreshState.OK,
  }) : super(
            controlFinishLoad: commControlFinishLoad,
            controlFinishRefresh: commControlFinishRefresh);

  setOperStatus({
    required int curPage,
    int? existDataLength,
    int? curDataLength,
    bool? isError,
    int? pageSize,
  }) {
    if ((isError ?? false)) {
      if (curPage == 1) {
        print('setOperStatus----------->0');
        this.finishRefresh(IndicatorResult.fail);
        state = RefreshState.HEAD_ERROR;
        Future.delayed(Duration(milliseconds: 1500), () {
          print('setOperStatus----------->00');
          // this.closeHeaderSecondary();
        });

      } else {
        print('setOperStatus----------->1');
        this.finishLoad(IndicatorResult.fail);
        state = RefreshState.FOOT_ERROR;
        Future.delayed(Duration(milliseconds: 1000), () {
          // this.resetFooter();
          // this.closeFooterSecondary();
        });

      }
    } else {
      if (curPage == 1) {
        this.finishRefresh();
        this.resetFooter();
      }
      if (((existDataLength ?? 0) == 0)) {
        if (curPage == 1) {
          print('setOperStatus----------->2');
          this.finishRefresh(IndicatorResult.none);
          this.finishLoad(IndicatorResult.none);
          // this.resetHeader();
          // this.resetFooter();
          state = RefreshState.HEAD_EMPTY;
        } else {
          print('setOperStatus----------->3');
          this.finishLoad(IndicatorResult.none);
          state = RefreshState.FOOT_EMPTY;
        }
      } else {
        if (((curDataLength ?? 0) < (pageSize ?? 10))) {
          if (curPage == 1) {
            print('setOperStatus----------->4');
            this.finishRefresh(IndicatorResult.success);
            Future.delayed(Duration(milliseconds: 1500), () {
              this.finishLoad(IndicatorResult.noMore);
            });
            state = RefreshState.NOT_ENOUGHPAGESIZE_HEAD;
          } else {
            print('setOperStatus----------->5');
            this.finishLoad(IndicatorResult.noMore);
            state = RefreshState.NOT_ENOUGHPAGESIZE_FOOT;
          }
        } else {
          if (curPage == 1) {
            print('setOperStatus----------->6');
            this.finishRefresh(IndicatorResult.success);
            state = RefreshState.OK;
          } else {
            print('setOperStatus----------->7');
            state = RefreshState.OK;
            this.finishLoad(IndicatorResult.success);
          }
        }
      }
    }
  }
}

class CommRefreshUtil {
  static init(
    CommRefreshController refreshController,
     {
    Key? key,
      required Widget childWidget,
     VoidCallback? onRefresh,
     VoidCallback? onLoad,
    bool? enablePullDown,
    bool? enablePullUp,
    bool? reverse,
    ScrollPhysics? physics,
    Widget? errorWidget,
    Widget? emptyWidget,
    Widget? notNetWidget,
    VoidCallback? onReLoadData,
    VoidCallback? onReFreshFunction,
    ScrollController? scrollController,
    bool? noMoreShow,
  }) {
    final footerHndicatorResult = (refreshController.footerState?.result);
    final headerHndicatorResult = (refreshController.headerState?.result);
    print('---->footerHndicatorResult 0 =$footerHndicatorResult');
    print('---->headerHndicatorResult 0 =$headerHndicatorResult');
    print('---->state =${refreshController?.state}');
    return EasyRefresh(
      key: key,
      header: ClassicHeader(
        iconTheme: IconThemeData(color: Color(0xff1BD9D9)),
        textStyle: TextStyle(
            fontSize: px_base_14,
            color: Color(0xff555555)
        ),
        messageStyle: TextStyle(
            fontSize: px_base_14,
            color: Color(0xff555555)
        ),
        dragText: '下拉刷新',
        armedText: '释放开始',
        readyText: '数据加载中...',
        processingText: '数据加载中...',
        processedText: '加载成功',
        noMoreText: '没有更多数据哦~',
        failedText: '加载失败',
        messageText: '最后更新于 %T',
      ),
      footer: ClassicFooter(
          iconTheme: IconThemeData(color: Color(0xff1BD9D9)),
          dragText: '下拉刷新',
          armedText: '释放开始',
          readyText: '数据加载中...',
          processingText: '数据加载中...',
          processedText: '加载成功',
          noMoreText: '没有更多数据哦~',
          failedText: '加载失败',
          messageText: '最后更新于 %T',
          textStyle: TextStyle(
              fontSize: px_base_14,
              color: Color(0xff555555)
          ),
          messageStyle: TextStyle(
              fontSize: px_base_12,
              color: Color(0xff555555)
          ),
          // showMessage: refreshController.footerState?.result != IndicatorResult.noMore,
          // noMoreIcon: refreshController.footerState?.result == IndicatorResult.noMore?SizedBox(width: 0,):null,
        showMessage: refreshController.state != RefreshState.NOT_ENOUGHPAGESIZE_FOOT,
        noMoreIcon: refreshController.state == RefreshState.NOT_ENOUGHPAGESIZE_FOOT?SizedBox(width: 0,):null,
      ),
      // clipBehavior: Clip.none,
      controller: refreshController,
      onRefresh:
          // (refreshController.state == RefreshState.HEAD_ERROR||
          // refreshController.state == RefreshState.FOOT_ERROR)?null:
          onRefresh,
      // onLoad: (refreshController.footerState?.result == IndicatorResult.noMore)? ((noMoreShow??false)?onLoad:null):(onLoad),
      onLoad: getOnLoadFunc(refreshController,noMoreShow??false,onLoad),
      child: _getChildUi(refreshController,childWidget,errorWidget,emptyWidget,notNetWidget,onReFreshFunction),
    );
  }

 static Widget _getChildUi(
      CommRefreshController refreshController,
      Widget childWidget,
      Widget? errorWidget,
      Widget? emptyWidget,
      Widget? notNetWidget,
      VoidCallback? onReFreshFunction) {
    final footerHndicatorResult = (refreshController.footerState?.result);
    final headerHndicatorResult = (refreshController.headerState?.result);
    print(
        '------footerHndicatorResult=$footerHndicatorResult,headerHndicatorResult=$headerHndicatorResult,');

    Widget childUi = childWidget == null
        ? Container(
      child: Center(
        child: Text(
          '',
          style: TextStyle(color: Colors.white),
        ),
      ),
    ) : childWidget;
    if (refreshController?.state == RefreshState.OK) {
      childUi = childWidget == null
          ? Container(
        child: Center(
          child: Text(
            '',
            style: TextStyle(color: Colors.white),
          ),
        ),
      )
          : childWidget;
    } else if (refreshController?.state == RefreshState.HEAD_EMPTY) {
      childUi = emptyWidget == null
          ? ListView(
        children: [
          Container(
            height: pxScreenHeight()-px_appBarHeight-pxStatusBarHeight(),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ImageUtil.loadAssetImage(
                      drawable_base_icon_nodata_img,
                      width: pxScreenWidth() * 1 / 2,
                      fit: BoxFit.fitWidth,
                      isOrigin: true),
                ],
              ),
            ),
          )
        ],
      ) : emptyWidget;
    }
    else if (headerHndicatorResult == IndicatorResult.fail ||
        footerHndicatorResult == IndicatorResult.fail) {
      childUi = errorWidget == null
          ?  ListView(
            children: [
              Container(
                height: pxScreenHeight()-px_appBarHeight-pxStatusBarHeight(),
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      ImageUtil.loadAssetImage(
                          drawable_base_icon_net_error,
                          width: pxScreenWidth() * 1 / 4,
                          fit: BoxFit.fitWidth,
                        color: Color(0xff1BD9D9)
                      ),
                      Container(
                        margin: EdgeInsets.only(top: px_base_5),
                        child: Text(
                          '${neterror}',
                          style: TextStyle(
                              color: Color(0xff666666)
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          )
          : errorWidget;
    }
    return childUi;
  }

  static getOnLoadFunc(CommRefreshController refreshController,noMoreShow,onLoad) {
    print('--------->noMoreShow=$noMoreShow');
    if(refreshController?.state == RefreshState.HEAD_ERROR)return null;
    if(refreshController?.state == RefreshState.FOOT_ERROR)return null;
    if(refreshController?.state == RefreshState.HEAD_EMPTY)return null;
    if(refreshController?.state == RefreshState.NOT_ENOUGHPAGESIZE_HEAD)return null;
    if(refreshController?.state == RefreshState.NOT_ENOUGHPAGESIZE_FOOT&&(!noMoreShow))return null;
    return onLoad;
  }
}
